//
//  HomeSelectionViewController.m
//  GiftNote
//
//  Created by lanou on 15/8/12.
//  Copyright (c) 2015年 GN. All rights reserved.
//

#import "HomeSelectionViewController.h"
#import "HomeHeader.h"
#import "HomeGiftCell.h"
#import "HomeSelectionHeadView.h"
#import "LORequestManger.h"
#import "HomeWheelModel.h"
#import "HomeBeautyModel.h"
#import "MJRefresh.h"
#import "HomeBaseDetailViewController.h"
#import "FMDB.h"

typedef NS_ENUM(NSInteger, RefreshDownLoadType) {
    RefreshDownLoadTypeUp,    // 下拉刷新
    RefreshDownLoadTypeDown   // 上拉加载
};

@interface HomeSelectionViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;        //  整个界面的UI
@property (nonatomic, strong) NSMutableArray *cellArray;     //  tableView的cell的数据的数组
@property (nonatomic, strong) NSMutableArray *wheelArray;    //  轮播图的数据数组
@property (nonatomic, strong) NSMutableArray *beautyArray;   //  美好小物的数据数组

@property (nonatomic, strong) HomeBaseDetailViewController *baseDVC;  //  点击tableView的cell进入下一个界面
@property (nonatomic, strong) HomeSelectionHeadView *headView;        //  tableView的头视图

@property (nonatomic, assign) int num;  //  上拉加载一次出现的记录个数
@property (nonatomic, assign) RefreshDownLoadType refreshDownLoadType;  // 刷新的类型
@property (nonatomic, strong) FMDatabase *db;  //  数据库实例化

@end




@implementation HomeSelectionViewController
#pragma mark --- 懒加载
- (NSMutableArray *)cellArray{
    
    if (_cellArray == nil) {
        self.cellArray = [NSMutableArray array];
    }
    return _cellArray;
}

- (NSMutableArray *)wheelArray{
    
    if (_wheelArray == nil) {
        
        self.wheelArray = [NSMutableArray array];
    }
    return _wheelArray;
}

- (NSMutableArray *)beautyArray{
    
    if (_beautyArray == nil) {
        
        self.beautyArray = [NSMutableArray array];
    }
    return _beautyArray;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    _num = 0;
    
    //  创建精品界面的tableView
    [self creatTableView];

    //
    [self readScrollData];
    [self readBeautyData];
    
    //  为cell解析数据
    [self readCellData];
    
    [self creatDocumentPath];
    [self searchFromDocument];
}



#pragma mark - 创建Table View
- (void)creatTableView{
    
    CGFloat height = self.navigationController.navigationBar.frame.size.height;
    
    _tableView  = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kHomeWidth, kHomeHeight - height - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.rowHeight = 273 * (kHomeWidth - 20) / 600 + 20;
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[HomeGiftCell class] forCellReuseIdentifier:@"HomeGiftCell"];
    
    
    //  设置_tableView的头视图
    _headView = [[HomeSelectionHeadView alloc] initWithFrame:CGRectMake(0, 0, kHomeWidth, kHomeHeight / 4 + kHomeWidth / 4)];
    _headView.naVC = _naVC;
    _tableView.tableHeaderView = _headView;
    
    
    //  添加上拉加载、下拉刷新的代理和实现响应的方法
    [_tableView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(headDownLoad)];
    [_tableView addGifFooterWithRefreshingTarget:self refreshingAction:@selector(footDownLoad)];
}



#pragma mark - TableViewDelegate/TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _cellArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeGiftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeGiftCell"];
    UIView *view = [[UIView alloc]initWithFrame:cell.frame];
    cell.selectedBackgroundView = view;
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    cell.giftModel = _cellArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeGiftModel *giftModel = _cellArray[indexPath.row];
    
    _baseDVC = [[HomeBaseDetailViewController alloc]init];
    _baseDVC.ID = [NSString stringWithFormat:@"%d",[giftModel.ID intValue]];
    _baseDVC.hidesBottomBarWhenPushed = YES;
    [_naVC pushViewController:_baseDVC animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}





#pragma mark - 数据请求

- (void)readScrollData{
    
    NSString *url = kHomeWheel;
    [LORequestManger GET:url success:^(id response) {
        
        [self deleteWheel];
        // 把原来数据库赋值的先删除
        for (UIImageView *imageView in [_headView.scrollView subviews]) {
            [imageView removeFromSuperview];
        }
        [self.wheelArray removeAllObjects];
        
        NSDictionary *dic = (NSDictionary *)response;
        NSArray *array = dic[@"data"][@"banners"];
        for (NSDictionary *newDic in array) {
            HomeWheelModel *wheelModel = [[HomeWheelModel alloc]init];
            [wheelModel setValuesForKeysWithDictionary:newDic];
            [self.wheelArray addObject:wheelModel];
            [self addDocumentWheelModel:wheelModel];
        }
        
        //  给轮播图界面传数组
        _headView.headScrollArray = _wheelArray;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)readBeautyData{
    
    [LORequestManger GET:kHomeBeauty success:^(id response) {
        
        [self deleteBeauty];
        [self.beautyArray removeAllObjects];
        
        NSDictionary *dic = (NSDictionary *)response;
        NSArray *array = dic[@"data"][@"promotions"];
        for (NSDictionary *newDic in array) {
            HomeBeautyModel *beauty = [[HomeBeautyModel alloc]init];
            [beauty setValuesForKeysWithDictionary:newDic];
            [self.beautyArray addObject:beauty];
            [self addDocumentBeautyModel:beauty];
            
        }
        
        //  给美好小物传数组
        _headView.headBeautyArray = _beautyArray;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)readCellData
{
    NSString *newUrl = [kHomeSelection stringByAppendingString:[NSString stringWithFormat:@"%d",_num]];
    [LORequestManger GET:newUrl success:^(id response) {
        
        if (_refreshDownLoadType == RefreshDownLoadTypeUp) {
            [_cellArray removeAllObjects];
            [self deleteGif];
        }
        
        NSDictionary *dic = (NSDictionary *)response;
        NSArray *items = dic[@"data"][@"items"];
        for (NSDictionary *newDic in items) {
            HomeGiftModel *giftModel = [[HomeGiftModel alloc]init];
            [giftModel setValuesForKeysWithDictionary:newDic];
            [self.cellArray addObject:giftModel];
            [self addDocumentGifModel:giftModel];
        }
        
        [_tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}




#pragma mark --- action
- (void)headDownLoad{
    
    _num = 0;
    _refreshDownLoadType = RefreshDownLoadTypeUp;
    [self readCellData];
    [_tableView.header endRefreshing];
}

- (void)footDownLoad{
    
    _num += 20;
    _refreshDownLoadType = RefreshDownLoadTypeDown;
    [self readCellData];
    [_tableView.footer endRefreshing];
}




#pragma mark - 本地缓存数据库
// 创建数据库
- (void)creatDocumentPath{
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]stringByAppendingPathComponent:@"Home.db"];
//    NSLog(@"%@",path);
    _db = [FMDatabase databaseWithPath:path];
    
    if (![_db open]) {
        NSLog(@"打开数据库失败");
    }
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS HomeGifList (id integer PRIMARY KEY, Cover_image_url text, Title text, Likes_count integer)"];
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS HomeWheelList (id integer PRIMARY KEY, Image_url text)"];
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS HomeBeautyList (id integer PRIMARY KEY, Icon_url text, Title text)"];
}


// 添加数据库
- (void)addDocumentGifModel:(HomeGiftModel *)gifModel{
    
    [_db executeUpdate:@"INSERT INTO HomeGifList (Cover_image_url, Title, Likes_count) VALUES (?,?,?)",gifModel.cover_image_url,gifModel.title,gifModel.likes_count];
}

- (void)addDocumentWheelModel:(HomeWheelModel *)wheelModel{
    
    [_db executeUpdate:@"INSERT INTO HomeWheelList (Image_url) VALUES (?)",wheelModel.image_url];
}

- (void)addDocumentBeautyModel:(HomeBeautyModel *)beautyModel{
    
    [_db executeUpdate:@"INSERT INTO HomeBeautyList (Icon_url, Title) VALUES (?,?)",beautyModel.icon_url,beautyModel.title];
}


// 删除数据库
- (void)deleteGif{
    
    [_db executeUpdate:@"DELETE FROM HomeGifList"];
}

- (void)deleteWheel{
    
    [_db executeUpdate:@"DELETE FROM HomeWheelList"];
}

- (void)deleteBeauty{
    
    [_db executeUpdate:@"DELETE FROM HomeBeautyList"];
}


// 查找数据库
- (void)searchFromDocument{
    
    FMResultSet *gifRs = [_db executeQuery:@"SELECT * FROM HomeGifList"];
    while ([gifRs next]) {
        HomeGiftModel *gifModel = [[HomeGiftModel alloc]init];
        gifModel.cover_image_url = [gifRs stringForColumn:@"Cover_image_url"];
        gifModel.title = [gifRs stringForColumn:@"Title"];
        gifModel.likes_count = [NSNumber numberWithInt:[gifRs intForColumn:@"Likes_count"]];
        [self.cellArray addObject:gifModel];
    }
    [gifRs close];
    
    
    FMResultSet *wheelRs = [_db executeQuery:@"SELECT * FROM HomeWheelList"];
    while ([wheelRs next]) {
        HomeWheelModel *wheelModel = [[HomeWheelModel alloc]init];
        wheelModel.image_url = [wheelRs stringForColumn:@"Image_url"];
        [self.wheelArray addObject:wheelModel];
    }
    _headView.headScrollArray = self.wheelArray;
    [wheelRs close];
    
    
    FMResultSet *beautyRs = [_db executeQuery:@"SELECT * FROM HomeBeautyList"];
    while ([beautyRs next]) {
        HomeBeautyModel *beautyModel = [[HomeBeautyModel alloc]init];
        beautyModel.icon_url = [beautyRs stringForColumn:@"Icon_url"];
        beautyModel.title = [beautyRs stringForColumn:@"Title"];
        [self.beautyArray addObject:beautyModel];
    }
    _headView.headBeautyArray = self.beautyArray;
    [beautyRs close];
    
}

@end
